﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using Mani.Common;
using Ghasam.Business.Services;
using Ghasam.Business.Domain.Entity;
using System.Collections.Generic;

public partial class NewInvoice : BasePage
{
    public override string ActionName {
        get {
            return "vw_newinvoice";
        }
    }
    private ICustomerService customerService;
    private IGoodsService goodsService;
    private IInvoiceService invoiceService;
    private CrystalReportManager manager;

    public IInvoiceService InvoiceService
    {
        get { return invoiceService; }
        set { invoiceService = value; }
    }
	
    public IGoodsService GoodsService
    {
        get { return goodsService; }
        set { goodsService = value; }
    }

    public ICustomerService CustomerService
    {
        get { return customerService; }
        set { customerService = value; }
    }
	
	

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) {
            LoadGoods();
            LoadCustomers();
        }
    }

    private void LoadGoods() {
        ddlGoods.DataSource = goodsService.GetGoods(1000, 0);
        ddlGoods.DataTextField = "Name";
        ddlGoods.DataValueField = "Id";
        ddlGoods.DataBind();
    }

    private void LoadCustomers() {
        Customer exampleCustomer = new Customer();
        exampleCustomer.IsDeleted = false;
        exampleCustomer.IsActive = true;

        if (!CommonHelper.ShowHiddenCustomers())
            exampleCustomer.IsFormal = true;

        ddlCustomers.DataSource = customerService.GetCustomers(exampleCustomer, 1000, 0);
        ddlCustomers.DataTextField = "CustomerName";
        ddlCustomers.DataValueField = "Id";
        ddlCustomers.DataBind();
    }

    protected void sdCustomer_Selecting( object sender, SqlDataSourceSelectingEventArgs e ) {
        bool show = CommonHelper.ShowHiddenCustomers();
        e.Command.Parameters["@IsFormal"].Value = 0;

        if (show) {
            e.Command.Parameters["@IsFormal"].Value = -1;
        }
    }

    protected void btnSave_Click( object sender, EventArgs e ) {

        if (ddlGoods.SelectedValue == "-1")
            return;

        CalculatePrice();

        Single NetWeight = -1;
        Single unitPrice = -1;
        Single TotalPrice = Convert.ToSingle(txtTotalPrice.Text); ;
        Single grossWeight = -1;
        Single emptyWeight = -1;

        if (!Single.TryParse(txtGrossWeight.Text, out grossWeight) || !Single.TryParse(txtEmptyWeight.Text, out emptyWeight))
            UIHelper.ClientAlert( this.Page, "لطفا یک عدد را به عنوان وزن وارد کنید" );

        NetWeight = grossWeight - emptyWeight;

        Goods goods = goodsService.GetGoods(Convert.ToInt32(ddlGoods.SelectedValue));
        unitPrice = goods.UnitPrice.Value;
        int customerId = Convert.ToInt32(ddlCustomers.SelectedValue);
        
        bool isFormal = true;
        Customer customer = null;

        if (customerId != -1) {
            customer = customerService.FindCustomer(customerId);
            isFormal = customer.IsFormal.Value;
        }

        Invoice invoice = new Invoice();

        invoice.Customer = customer;
        invoice.OneTimeCustomer = txtOneTimeCustomer.Text;
        invoice.IsFormal = isFormal;
        invoice.Goods = goods;
        invoice.GrossWeight = Convert.ToSingle( txtGrossWeight.Text );
        invoice.EmptyWeight = Convert.ToSingle( txtEmptyWeight.Text );
        invoice.NetWeight = Convert.ToSingle( txtNetWeight.Text );
        invoice.VehicleNo = txtVehicleNumber.Text;
        invoice.UnitCost = unitPrice;
        invoice.TotalPrice = TotalPrice;
        invoice.LastUpdate = DateTime.Now;
        invoice.InvoiceDate = DateTime.Now;

        invoiceService.NewInvoice(invoice, rbCash.Checked);
        lblMessage.Text = "صورتحساب با موفقیت ذخیره شد";
        ResetForm();

        Response.Redirect("rpt/InvoiceReport.aspx?InvoiceId=" + invoice.Id.ToString());
    }

    protected void ddlCustomers_SelectedIndexChanged( object sender, EventArgs e ) {
        Customer customer = customerService.FindCustomer(Convert.ToInt32(ddlCustomers.SelectedValue));

        if ( !customer.WarningPrice.HasValue )
            return;

        //string q = "Select WarningPrice FROM Customer WHERE Id=" + ddlCustomers.SelectedValue;
        //q = "Select SUM(Credit) - SUM(Debit) FROM Accounting WHERE CustomerId=" + ddlCustomers.SelectedValue;

        if (customer.Balance.Value < customer.WarningPrice.Value)
        {
            UIHelper.ClientAlert(this.Page, "این مشتری به مبلغ هشدار رسیده است تراز فعلی " + UIHelper.FormatString(customer.Balance.Value.ToString()) + "می باشد");
        }

    }

    private void CalculatePrice() {
        Single unitPrice;
        Single NetWeight = -1;
        Single TotalPrice = -1;
        Single grossWeight = -1;
        Single emptyWeight = -1;


        if (!Single.TryParse(txtGrossWeight.Text, out grossWeight) || !Single.TryParse(txtEmptyWeight.Text, out emptyWeight))
            UIHelper.ClientAlert( this.Page, "لطفا یک عدد را به عنوان وزن وارد کنید" );

        NetWeight = grossWeight - emptyWeight;
        txtNetWeight.Text = NetWeight.ToString();

        Goods goods = goodsService.GetGoods(Convert.ToInt32(ddlGoods.SelectedValue));
        unitPrice = goods.UnitPrice.Value;
        txtUnitPrice.Text = unitPrice.ToString();
        TotalPrice = unitPrice * NetWeight;
        txtTotalPrice.Text = TotalPrice.ToString();
        txtTotalPrice.ReadOnly = (!goods.IsDiscountable.Value);
    }

    protected void rbCash_CheckedChanged( object sender, EventArgs e ) {
        if (rbCash.Checked) {
            txtOneTimeCustomer.Enabled = true;
            ddlCustomers.Enabled = false;
        }
    }

    protected void rbNotCash_CheckedChanged( object sender, EventArgs e ) {
        if (rbNotCash.Checked) {
            ddlCustomers.Enabled = true;
            txtOneTimeCustomer.Enabled = false;
        }
    }

    protected void ddlGoods_SelectedIndexChanged( object sender, EventArgs e ) {
        if ( ddlGoods.SelectedValue != "-1" )
            CalculatePrice();
    }

    private void ResetForm() {
        rbCash.Checked = false;
        txtOneTimeCustomer.Text = "";
        txtOneTimeCustomer.Enabled = false;
        ddlCustomers.Enabled = false;
        ddlCustomers.SelectedIndex = -1;
        rbNotCash.Checked = false;
        txtVehicleNumber.Text = "";
        txtGrossWeight.Text = "";
        ddlGoods.SelectedIndex = -1;
        txtEmptyWeight.Text = "";
        txtNetWeight.Text = "";
        txtUnitPrice.Text = "";
        txtTotalPrice.Text = "";
    }

    protected void Page_Unload(object sender, EventArgs e) {
        if (manager != null)
            manager.Dispose();
    }
}
